import React from 'react';
import $ from 'jquery';
import _ from 'underscore';
import deepExtend from 'lib/util/deepExtend';
import Highcharts from 'highcharts';

Highcharts.setOptions({
  global: {
    useUTC: false
  },
  colors:['#56bc76','#eac85e','#32adfa','#c596fa','#70e0e0','#a1e55c','#f2a38d','#ffe9a6','#7aa9ff','#e5603b']
});
var defaultOption = {
  chart:{
    spacing:[15,0,0,0],
    backgroundColor:'rgba(0, 0, 0, 0)',
    plotBorderWidth:0,
    style:{
      fontFamily: '"Open Sans", "Hiragino Sans GB", "Microsoft Yahei", sans-serif'
    }
  },
  title: {
    text: null
  },
  credits:{
    enabled:false
  },
  legend:{
    align:'center',
    itemStyle: {
      color:'#f8f8f8',
      fontWeight: 'normal',
      fontSize: 12,
      width: 150,
      textOverflow: "ellipsis",
      overflow: "hidden",
      whiteSpace: "nowrap"
    },
    itemHoverStyle: {color: "#f8f8f8",fontWeight: "bold"},
    itemHiddenStyle: {color: "rgba(255,255,255,0.4)"},
    symbolHeight: 8,
    symbolWidth: 12,
    fontFamily: '"Open Sans", "Hiragino Sans GB", "Microsoft Yahei", sans-serif'
  },
  loading:{},
  xAxis: [{
    type:'datetime',
    minPadding:0,
    maxPadding:0,
    minTickInterval:60*1000,
    labels:{
      // useHTML:true,
      style:{
        color:'rgba(248,248,248,1)',
        fontWeight: '300',
        fontSize: 11,
        whiteSpace: 'nowrap',
        fontFamily: '"Open Sans", sans-serif'
      }
    },
    dateTimeLabelFormats:{
      millisecond: '%H:%M',
      second: '%H:%M',
      minute: '%H:%M',
      hour: '%H:%M',
      day: '%b/%e',
      week: '%b/%e',
      month: '%Y/%b',
      year: '%Y'
    }
  }],
  yAxis: [{
    title: {
      text: null
    },
    gridLineColor:'rgba(0,0,0,0.1)',
    min:0,
    // showLastLabel:false,
    labels:{
      // useHTML:true,
      style:{
        color:'rgba(248,248,248,1)',
        whiteSpace: 'nowrap',
        fontSize: 11,
        fontWeight: '400',
        fontFamily: '"Open Sans", sans-serif'
      }
    },
    offset:0,
    minPadding:0,
    tickPosition:'outside'
  }],
  tooltip:{
    // shared: true,
    crosshairs:[{
      width:1,
      color:'rgba(0,0,0,0.1)',
      zIndex:3
    },false],
    // useHTML:true,
    style: {color: '#fff',fontSize: 12},
    borderWidth: 0,
    shadow: false,
    backgroundColor:'rgba(0,0,0,0.4)',
    borderRadius: 5,
    zIndex:8
  },
  series: [],
  plotOptions:{
    pie:{
      animation:false,
      dataLabels: {color: '#fff',shadow: false,fontWeight: 'normal',padding:0,connectorPadding:0,style:{width:40}},
      stickyTracking:true
    },
    spline:{
      lineWidth:2.5,
      marker:{
        radius: 1,
        lineWidth: 1
      }
    },
    line:{
      lineWidth:2.5,
      marker:{
        radius: 2.5,
        lineWidth: 1,
        lineColor: 'transparent'
      }
    },
    area:{
      lineColor: 'rgba(0,0,0,0.1)',
      connectEnds:false,
      fillOpacity:0.9,
      lineWidth:0.5,
      stacking:'normal',
      marker:{
        radius: 0,
        lineWidth: 1,
        symbol:"circle"
      }
    },
    series:{
      dashStyle: "solid",
      pointInterval: 60000,
      borderColor: '#fff'
      // fillOpacity:0.3,
    },
    bar:{
      stacking:'percent',
      pointInterval:1
    },
    columnrange:{
      pointInterval:1
    }
  }
}
var whiteBgMixin = {
  legend:{
    itemStyle:{
      color:'#666666'
    },
    itemHoverStyle: {color: "#666666",fontWeight: "bold"},
    itemHiddenStyle: {color: "rgba(102,102,102,0.5)"}
  },
  plotOptions: {
    pie:{
      dataLabels: {color: '#666'}
    }
  },
  tooltip:{
    style: {color: '#666',fontSize: 12},
    shadow: true,
    backgroundColor:'rgba(248,248,248,0.95)'
  },
  yAxis:{
    labels:{
      style:{
        color:'rgba(102,102,102,1)',
        fontWeight: 300
      }
    }
  },
  xAxis:{
    labels:{
      style:{
        color:'rgba(102,102,102,1)',
        fontWeight: 300
      }
    }
  }
}
var HighchartsComponent = module.exports = React.createClass({
  displayName: 'Highcharts',
  renderChart: function () {
    var config = this.state
      , el = this.refs.root
      , isWhiteBg = $(el).parents('.widget-float').length

    config = deepExtend({},config, {
      chart: {
        renderTo: el
      }
    });
    if(isWhiteBg){
      config = deepExtend({}
                , config
                , _.omit(whiteBgMixin,'yAxis','xAxis')
                , {
                  xAxis:config.xAxis.map(function(xAxis){
                    return deepExtend({},xAxis,whiteBgMixin.xAxis)
                  }),
                  yAxis:config.yAxis.map(function(yAxis){
                    return deepExtend({},yAxis,whiteBgMixin.yAxis)
                  })
                })
    }
    // console.log(config)
    return new Highcharts.Chart(config);
  },
  getDefaultProps:function(){
    return {
      height:200,
      yAxis:[{}],
      xAxis:[{}]
    }
  },
  parseToPie:function(series){
    return [{
      data:_(series).map(function(serie){
        return {
          id:serie.id,
          name:serie.name,
          y:serie.data[0]&&serie.data[0].y,
          customData:serie.data[0]&&serie.data[0].customData
        }
      })
    }]
  },
  getInitialState:function(){
    var yAxises = _.isArray(this.props.yAxis)?this.props.yAxis:[this.props.yAxis]
      , xAxises = _.isArray(this.props.xAxis)?this.props.xAxis:[this.props.xAxis]
    var chartType = this.props.chart.type
    var finalOptions = _.extend({},defaultOption,{
      chart:deepExtend({},defaultOption.chart,this.props.chart),
      series:chartType==='pie'?this.parseToPie(this.props.series):this.props.series,
      yAxis:yAxises.map(function(yAxis){
        return deepExtend({},defaultOption.yAxis[0],yAxis,this.props.chartSettings.yAxis)
      },this),
      xAxis:xAxises.map(function(xAxis){
        return deepExtend({},defaultOption.xAxis[0],xAxis,this.props.chartSettings.xAxis)
      },this),
      tooltip:_.extend({},defaultOption.tooltip,this.props.tooltip)
    })

    return deepExtend({},finalOptions,_(this.props.chartSettings).omit('yAxis','xAxis'));
  },
  componentWillReceiveProps:function(nextProps,prevProps){
    var newSeriesNames = _(nextProps.series).pluck('name')
    if(this.state.chart.type!=='pie'){
      this.chart.series.filter(function(s){
        return !_.contains(newSeriesNames,s.name)
      }).forEach(function(s){
        s.remove();
      });
      var oldSeriesNames = _(this.chart.series).pluck('name')
      var partNew = _.partition(nextProps.series,function exists(s){
        return _.contains(oldSeriesNames,s.name)
      });
      var existedSeries = partNew[0]
        , newSeries = partNew[1]

      existedSeries.forEach(function(serie){
        var oldSerie = _(this.chart.series).findWhere({'name':serie.name})
        oldSerie.update(serie,false);
      },this);

      newSeries.forEach(function(s){
        this.chart.addSeries(s,false,false);
      },this);
      this.chart.redraw();
    } else {
      let series = this.parseToPie(nextProps.series);
      if (series.length && this.chart.series.length) {
        this.chart.series[0].update(series[0], true);
      }
    }
  },
  componentDidMount: function () {
    this.chart = this.renderChart();
  },
  componentWillUnmount: function () {
    this.chart.destroy();
    this.chart = null;
  },
  render: function () {
    return <div ref="root"/>
  }
});
